from django.contrib import admin
from django.utils.html import format_html
from .models import User, Project, Building, News, Announcement, Sensor, Gateway, Calibration, Alert, DataPoint
from import_export.admin import ImportExportMixin
from import_export import resources

# 用户管理
class UserResource(resources.ModelResource):
    class Meta:
        model = User
        fields = ('username', 'role', 'phone', 'department', 'email')

@admin.register(User)
class UserAdmin(ImportExportMixin, admin.ModelAdmin):
    resource_class = UserResource
    list_display = ('username', 'role', 'phone', 'department')
    list_filter = ('role', 'department')
    search_fields = ('username', 'phone')
    filter_horizontal = ('managed_projects', 'groups', 'user_permissions')

# 项目管理的资源类和Admin配置
class ProjectResource(resources.ModelResource):
    class Meta:
        model = Project
        fields = ('name', 'code', 'location', 'start_date', 'end_date')

@admin.register(Project)
class ProjectAdmin(ImportExportMixin, admin.ModelAdmin):
    resource_class = ProjectResource
    list_display = ('name', 'code', 'project_manager', 'start_date', 'location')
    search_fields = ('name', 'code', 'project_manager__username')
    list_filter = ('start_date', 'project_manager')
    fieldsets = (
        ('基础信息', {'fields': ('name', 'code', 'project_manager')}),
        ('工程详情', {'fields': ('location', 'start_date', 'end_date', 'description')}),
        ('区域配置', {'fields': ('zones', 'monitoring_areas', 'zone_details')})
    )

class BuildingInline(admin.TabularInline):
    model = Building
    extra = 1
    fields = ('name', 'building_type', 'location', 'construction_date')

ProjectAdmin.inlines = [BuildingInline]

# 以下模型按相同模式添加资源类配置
class BuildingResource(resources.ModelResource):
    class Meta:
        model = Building
        fields = ('name', 'project', 'location', 'building_type')

@admin.register(Building)
class BuildingAdmin(ImportExportMixin, admin.ModelAdmin):
    resource_class = BuildingResource
    list_display = ('name', 'project', 'get_project_manager', 'building_type', 'location')
    list_filter = ('project__name', 'building_type')
    search_fields = ('name', 'project__code', 'location')
    raw_id_fields = ('project',)
    fieldsets = (
        ('基础信息', {'fields': ('name', 'project', 'building_type')}),
        ('位置信息', {'fields': ('location', 'construction_date', 'section')}),
        ('监测配置', {'fields': ('monitoring_points', 'section_groups', 'section_details')})
    )

    def get_project_manager(self, obj):
        return obj.project.project_manager
    get_project_manager.short_description = '项目负责人'

class SensorInline(admin.TabularInline):
    model = Sensor
    extra = 1
    fields = ('name', 'sensor_type', 'status', 'installation_date')

BuildingAdmin.inlines = [SensorInline]

@admin.register(News)
class NewsAdmin(ImportExportMixin, admin.ModelAdmin):
    list_display = ('title', 'publish_date', 'is_published')
    list_filter = ('is_published', 'publish_date')
    search_fields = ('title', 'content')
    date_hierarchy = 'publish_date'

@admin.register(Announcement)
class AnnouncementAdmin(ImportExportMixin, admin.ModelAdmin):
    list_display = ('title', 'category', 'publish_date', 'is_published')
    list_filter = ('category', 'is_published', 'publish_date')
    search_fields = ('title', 'content')
    date_hierarchy = 'publish_date'

@admin.register(Sensor)
class SensorAdmin(ImportExportMixin, admin.ModelAdmin):
    list_display = ('name', 'building', 'sensor_type', 'status', 'installation_date', 'generate_qr_code')
    list_filter = ('sensor_type', 'status', 'building__project')
    search_fields = ('name', 'design_code', 'gateway', 'management_unit')
    raw_id_fields = ('building',)
    date_hierarchy = 'installation_date'
    fieldsets = (
        ('基础信息', {'fields': ('name', 'building', 'sensor_type', 'status')}),
        ('设备信息', {'fields': ('design_code', 'gateway', 'port_number', 'management_unit')}),
        ('技术参数', {'fields': ('measurement_range', 'accuracy', 'sampling_rate')}),
        ('维护信息', {'fields': ('installation_date', 'last_maintenance', 'manufacturer')})
    )

    def generate_qr_code(self, obj):
        return format_html(
            '<a href="/admin/sensor-qrcode/{}/" target="_blank">🔗 生成二维码</a>',
            obj.id
        )
    generate_qr_code.short_description = '二维码'

    def get_urls(self):
        from django.urls import path
        urls = super().get_urls()
        custom_urls = [
            path('sensor-qrcode/<int:pk>/', self.admin_site.admin_view(self.generate_qr_code_view),
                 name='sensor_qr_code')
        ]
        return custom_urls + urls

    def generate_qr_code_view(self, request, pk):
        # 二维码生成逻辑
        from django.http import HttpResponse
        import qrcode
        from io import BytesIO
        
        sensor = Sensor.objects.get(pk=pk)
        qr = qrcode.make(f'Sensor ID: {sensor.id}\nName: {sensor.name}\nType: {sensor.sensor_type}')
        buffer = BytesIO()
        qr.save(buffer)
        return HttpResponse(buffer.getvalue(), content_type='image/png')

@admin.register(Gateway)
class GatewayAdmin(ImportExportMixin, admin.ModelAdmin):
    list_display = ('name', 'location', 'status', 'last_heartbeat')
    list_filter = ('status',)
    search_fields = ('name', 'location', 'ip_address')

@admin.register(Calibration)
class CalibrationAdmin(ImportExportMixin, admin.ModelAdmin):
    list_display = ('sensor', 'calibration_date', 'calibrated_by', 'next_calibration_date')
    list_filter = ('calibration_date', 'next_calibration_date')
    search_fields = ('sensor__name', 'calibrated_by')
    raw_id_fields = ('sensor',)
    date_hierarchy = 'calibration_date'

@admin.register(Alert)
class AlertAdmin(ImportExportMixin, admin.ModelAdmin):
    list_display = ('sensor', 'alert_type', 'alert_time', 'is_resolved')
    list_filter = ('alert_type', 'is_resolved', 'alert_time')
    search_fields = ('sensor__name', 'message')
    raw_id_fields = ('sensor',)
    date_hierarchy = 'alert_time'

@admin.register(DataPoint)
class DataPointAdmin(ImportExportMixin, admin.ModelAdmin):
    list_display = ('sensor', 'timestamp', 'value')
    list_filter = ('sensor__sensor_type', 'timestamp')
    search_fields = ('sensor__name',)
    raw_id_fields = ('sensor',)
    date_hierarchy = 'timestamp'
